#!/usr/bin/env bash

declare -a target_dir=("functional")
declare -i total passed skipped failed realnum
# 69 测试样例疑似有误
declare -a skip=("69" "77" "82" "83" "88" "96" "97" "98")

tmpir=tmpirgen
tmpout=tmpout
linked="linked"
sylib="lib/sylib.ll"

total=0
passed=0
skipped=${#skip[@]}
failed=0

prefix_mached_continue=false

cmake --build build -- -j 12

for dir in "${target_dir[@]}"; do
  for file in test/"$dir"/*.sy; do
    prefix_mached_continue=false
    total=$total+1
    basename=${file%.sy}
    if [ ! -f "$basename.out" ]; then
      echo -e "\e[33mSKIPPED\e[0m: $file"
      skipped=$skipped+1
      continue
    fi

    basename_no_path=$(basename "$basename")
    for prefix in "${skip[@]}"; do
      if [[ $basename_no_path == $prefix* ]]; then
        prefix_mached_continue=true
        break
      fi
    done

    if $prefix_mached_continue; then
      echo -e "\e[33mSKIPPED\e[0m: $file"
      continue
    fi

    if ! build/bin/sysyc "$file" >$tmpir; then
      echo -e "\e[31mIRGEN ERROR\e[0m: $file"
      failed=$failed+1
      continue
    fi
    llvm-link $sylib $tmpir -o $linked

    if [ -f "$basename.in" ]; then
      lli $linked >$tmpout <"$basename.in"
    else
      lli $linked >$tmpout
    fi

    ret=$?

    lastline=$(tail -n 1 "$tmpout")

    if [[ -z "$lastline" ]]; then
      echo $ret >>$tmpout
    else
      echo >>$tmpout
      echo $ret >>$tmpout
    fi

    # echo $? >>"$tmpout"

    if ! diff -Bw "$tmpout" "$basename.out" >/dev/null 2>&1; then
      echo -e "\e[31mIRRUN ERROR\e[0m: $file"
      failed=$failed+1
    else
      echo -e "\e[32mSUCCESS\e[0m: $file"
      passed=$passed+1
    fi
  done
done

realnum=$total-$skipped

echo "$passed/$realnum passed, $failed/$realnum failed, $skipped/$total skipped."
echo "all finished."
rm $tmpir $tmpout $linked
exit 0
